const express = require('express');
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");//浏览器的存储
const expressSession = require("express-session");//服务器端的传值
const uuid = require("uuid");
const cors = require("cors");
let app=express();
app.use(cors());
app.use("*",(request,response,next)=>{
    //请求的路径带api的字眼
    if(request.originalUrl.indexOf("/api") != -1){
        response.setHeader("Content-Type","application/json;charset=utf-8");
    }
    next();
})
//配置静态资源服务器
app.use(express.static("./../src/"));
//配置中间件
app.use(expressSession({
    genid:function(){
        return uuid.v1()
    },
    maxAge:1000*60*20,
    secret:"1000phone",
    resave:true,
    saveUninitialized:true
}));
app.use(cookieParser("1000phone"));

app.use(bodyParser.urlencoded({
    extended:false
}));
app.use(bodyParser.json());


// app.use("/api",require("./routes/adminRoute"));

let whiteList=['/api/login','/api/reg','/api/register','/api/goodslist','/api/goodsbyid'];
app.use("*",(request,response,next)=>{
    if(request.originalUrl == '/favicon.ico'){
        return;
    }
    if(request.originalUrl.indexOf("/api") !=-1){
        response.setHeader("Content-type","application/json;charset=utf-8");
    }
    if(request.session["userInfo"] == undefined || request.session["userInfo"]==null){
        let isPass = whiteList.some(el=>{
            return request.originalUrl.toLowerCase().indexOf(el.toLowerCase())!=-1
        })
        if(isPass){
            next()
        }else{
           
                response.json({
                    err:"请先登录",
                    status:-1
                })
            
        }
    }else{
        next();
    }
})
app.use("/api",require("./routes/apiRoute"));
app.listen(8080,()=>{
    console.log("服务器启动完毕");
})
